<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/8
 * Time: 12:16
 */

namespace app\admin\controller;
use app\admin\common\Base;
use think\facade\Request;

class Cate extends Base
{
    public function cateList(){
        $cateList = \app\admin\model\Cate::all(function($query){
            /*
             * CREATE TABLE `zh_article_category` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '用户主键',
  `name` varchar(60) NOT NULL DEFAULT '' COMMENT '栏目名称',
  `sort` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '栏目排序',
  `status` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '状态1:启用,0:禁用',
  `create_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
  `update_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',*/
            $query->field('id,name,status,sort,create_time');
        });
        $this->assign('cateList', $cateList);
        $this->assign('empty', '<h3>暂时没有查询到分类信息</h3>');
        return $this->view->fetch('catelist');
    }

    public function edit(){
        if (Request::isPost()){
            $data = Request::post();
            if (isset($data['id']) && $data['id']){
                # 更新
                $id = $data['id'];
                unset($data['id']);
                $data['update_time'] = time();
                $res = \app\admin\model\Cate::where('id',$id)->data($data)->update();
            }else{
                # 添加
                $data['create_time'] = time();
                $res = \app\admin\model\Cate::create($data);
            }
            if ($res){
                return $this->success('保存成功','cateList');
            }
            return $this->error('保存失败，请稍后再试');
        }
        $id = Request::param('id');
        $cate = null;
        if ($id){
            $cate = \app\admin\model\Cate::get($id);
            if (empty($cate)){
                return $this->error('非法访问');
            }
        }
        $this->assign('cateInfo', $cate);
        return $this->view->fetch();
    }

    public function doDel(){
        $id = Request::param('id');
        if (empty($id)){
            return $this->error('非法访问');
        }
        $res = \app\admin\model\Cate::destroy($id);
        if ($res){
            return $this->success('删除成功','cateList');
        }
        return $this->error('删除失败');
    }
}